#!/usr/bin/python

import pymysql
import time
import psutil

db = pymysql.connect(user='root',passwd='123123',host='localhost',db='sanle')
db.autocommit(True)
cur = db.cursor()

a_sent = psutil.net_io_counters().bytes_sent
a_recv = psutil.net_io_counters().bytes_recv

while 1:
    time.sleep(1)
    b_sent = psutil.net_io_counters().bytes_sent
    b_recv = psutil.net_io_counters().bytes_recv
    total_sent = b_sent - a_sent
    total_recv = b_recv - a_recv
    a_sent = b_sent
    a_recv = b_recv
    timestamp = int(time.time())
    print(timestamp,total_sent,total_recv)
    sql = "insert into nic(time, nic_in, nic_out) values({time},{a},{b})".format(time=timestamp,a=total_recv,b=total_sent)
    cur.execute(sql)
